package emt.friendtracking.locationmodule;

import java.util.ConcurrentModificationException;
import java.util.concurrent.CopyOnWriteArrayList;

import android.content.Context;
import android.location.LocationManager;
import emt.friendtracking.MyApplication;
import android.util.Log;

public class CoordinatesHandler
{
	private static CoordinatesHandler instance;
	private final static String TAG = CoordinatesHandler.class.getSimpleName();
	private volatile CopyOnWriteArrayList<CoordinatesUpdateListener> listeners = new CopyOnWriteArrayList<CoordinatesUpdateListener>();
	
	private CoordinatesHandler()
	{}
	
	public static CoordinatesHandler getCoordinatesHandler()
	{
		if (instance == null)
			instance = new CoordinatesHandler();
		return instance;
	}
	
	public void addCoordinatesListener(CoordinatesUpdateListener listener)
	{
		Log.d(TAG, "AddListener");
		listeners.add(listener);
	}
	
	public void removeCoordinatesListener(CoordinatesUpdateListener listener)
	{
		Log.d(TAG, "RemoveListener");
		try
		{
			listeners.remove(listener);
		}
		catch (ConcurrentModificationException e)
		{
			listeners.remove(listener);
		}
		if (listeners.size() == 0)
		{
			MyApplication.getAppContext();
			LocationIdentifier.getInstance((LocationManager) MyApplication.getAppContext().getSystemService(Context.LOCATION_SERVICE)).stopLocationSearching();
		}
	}
	
	public void fireCoordinatesEvent(Coordinates newCoordinates)
	{
		for (CoordinatesUpdateListener c : listeners)
		{
			c.onNewCoordinates(newCoordinates);
		}
	}
}
